import { init } from '../../node_modules/snabbdom/build/package/init.js'

import { h } from '../../node_modules/snabbdom/build/package/h.js'
import { classModule } from '../../node_modules/snabbdom/build/package/modules/class.js'
import { eventListenersModule } from '../../node_modules/snabbdom/build/package/modules/eventlisteners.js'
import mock from './mock.js';

const patch = init([
  classModule,
  eventListenersModule
]);
let vnode;
let movieVnode;
let data = mock.map(item => item);
function handleSort(item) {
  data = sort(data, item);
  movieVnode = patch(movieVnode, movieView(data));
}
function addItem() {
  data.unshift({
    rank: parseInt(Math.random() * 100),
    title: Math.random().toString(16).substring(2),
    desc: Math.random().toString(16).substring(2)
  });
  movieVnode = patch(movieVnode, movieView(data))
}
function deleteItem(item) {
  data = data.filter(movie => {
    return movie.rank !== item.rank;
  })
  movieVnode = patch(movieVnode, movieView(data))
}
function view(data) {
  const vnode = h('div.container', [
    h('div.header', 'Top 10 movies'),
    h('div.sort-line', [
      h('div.sort-by', 'Sort by:'),
      h('div.sort-item', ['rank', 'title', 'desc'].map(item => {
        return h('div', {
          on: {
            click: [handleSort, item]
          },
        }, item)
      })),
      h('div.add', {
        on: {
          click: addItem
        }
      }, 'Add')
    ]),
    movieView(data)
  ]);
  return vnode;
}

function movieView(list) {
  movieVnode = h('div.content-wrapper', list.map(item => {
    return h('div.content-item-wrapper', [...Object.keys(item).map(key => {
      return h('div.content-item', item[key]);
    }), h('div.delete', {
      on: {
        click: [deleteItem, item]
      }
    }, 'x')])
  }));
  return movieVnode;
}
function sort(data, key) {
  return data.sort((x, y) => {
    if (x[key] <y[key]) {
      return -1;
    }
    return 1;
  });
} 

window.addEventListener('DOMContentLoaded', () => {
  vnode = patch(document.querySelector('#container'), view(data));
});
